<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 员工页头 -->
      <page-header>
        <template #left>
          <span> 总记录数: {{ total }}条 </span>
        </template>
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/employees/upload-excel')"
          >excel上传</el-button>
          <el-button
            type="success"
            size="small"
            @click="handleDownload"
          >excel下载当前页</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDownloadAll"
          >excel下载所有页</el-button>
          <el-button
            v-if="$store.state.user.userInfo.roles.points.includes('point-add')"
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-header>
      <!-- 表格 -->
      <el-card style="margin-top: 10px">
        <el-table :data="employeeList" border stripe width="100%">
          <el-table-column
            label="序号"
            width="80"
            type="index"
            :index="indexMethod"
          />
          <el-table-column label="姓名" prop="username" width="120" />
          <el-table-column label="头像" width="120">
            <template #default="{ row }">
              <img
                v-imgerror="defaultImgUrl"
                :src="row.staffPhoto"
                width="50"
                @click="handleQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" width="120" />
          <el-table-column label="工号" prop="workNumber" width="120" />
          <el-table-column label="聘用形式" width="85">
            <template #default="{ row }">
              {{ formOfEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" width="120" />
          <el-table-column label="入职时间" prop="timeOfEntry" width="120" />
          <el-table-column label="账户状态" width="120">
            <template #default="{ row }">
              {{ formatEnableState(row.enableState) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="400">
            <template #default="{ row }">
              <el-button
                type="text"
                @click="$router.push(`/employees/${row.id}`)"
              >查看</el-button>
              <el-button type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button
                type="text"
                @click="handleOpen(row.id)"
              >角色</el-button>
              <el-button
                v-permission="'point-del'"
                type="text"
                @click="handleDel(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :total="total"
          :page-size="query.size"
          :current-page="query.page"
          :page-sizes="[3, 5, 8, 10]"
          layout="total,sizes,prev,pager,next,jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>

      <add-employee
        :show-dialog.sync="showDialog"
        @add-success="getEmployeeList"
      />
      <el-dialog title="二维码" :visible="isShow" @close="isShow = false">
        <!-- 这里展示二维码标签 -->
        <!-- 用来画二维码的 -->
        <canvas ref="qrCodeRef" />
      </el-dialog>

      <el-dialog title="分配角色" :visible="isShow2" @close="handleClose">
        <!--  -->
        <el-checkbox-group v-model="checkedRoleList">
          <!-- label: 两个用途，既是展示的文本，也是提供给v-model用的 -->
          <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
        <template #footer>
          <el-button size="small" @click="handleClose">取消</el-button>
          <el-button
            size="small"
            type="primary"
            @click="handleAssign"
          >确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AddEmployee from './components/add-employee.vue'
import obj from '@/constant/employees'
import defaultImgUrl from '@/assets/common/touxiang.png'
import {
  getEmployeeListAPI,
  delEmployeeAPI,
  getEmployeeInfoAPI,
  assignRoleAPI
} from '@/api/employees'
import { getRoleListAPI } from '@/api/setting'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import QrCode from 'qrcode'
export default {
  name: 'EmployeesView',
  components: {
    AddEmployee
  },
  data() {
    return {
      // 选中的角色列表
      checkedRoleList: [],
      // 所有的角色列表
      roleList: [],
      // 员工列表
      employeeList: [],
      // 数据总条数
      total: 0,
      query: {
        page: 1, // 页码
        size: 5 // 条数
      },
      // 员工默认头像
      defaultImgUrl,
      showDialog: false,
      isShow: false,
      isShow2: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 分配角色
    async handleAssign() {
      // 发起请求(把选中的角色同步到后台)
      await assignRoleAPI(this.employeeId, this.checkedRoleList)
      // 关闭弹框
      this.handleClose()
      // 给个成功的提示
      this.$message.success('分配角色成功')
    },
    // 获取员工列表
    async getEmployeeList() {
      // 发起获取员工请求
      const resp = await getEmployeeListAPI(this.query)
      console.log(resp)
      // 解构
      const { rows, total } = resp.data
      // 赋值
      this.employeeList = rows
      this.total = total
    },
    // 自定义下标
    indexMethod(index) {
      // 规则： 当前页数据的序号+ 1 + （当前页码 - 1） * 每条条数
      return index + 1 + (this.query.page - 1) * this.query.size
    },
    // 格式化聘用形式
    formOfEmployment(formOfEmployment) {
      // formatEmployment
      // if (formatEmployment === 1) {
      //   return '1'
      // } else if (formatEmployment === 2) {
      //   return '2'
      // }
      // 通过对象体现对应关系
      // const obj = {
      //   1: '正式工',
      //   2: '非正式',
      //   3: '实习工',
      //   4: '钟点工'
      // }
      // return obj[formOfEmployment]
      // 根据  formOfEmployment去hireType去找
      const item = obj.hireType.find((item) => item.id === formOfEmployment)
      // 三元： 如果找到了，返回对象的value属性 没有找到的返回未知
      return item ? item.value : '未知'
    },
    formatEnableState(enableState) {
      // 根据enableState去workingState中查找
      const item = obj.workingState.find((item) => item.id === enableState)

      return item ? item.value : '未知'
    },
    // 每页条数改变时
    handleSizeChange(val) {
      // 把选择的条数同步到query.size中
      this.query.size = val
      // 获取员工列表
      this.getEmployeeList()
    },
    handleCurrentChange(val) {
      // 把选择的条数同步到query.size中
      this.query.page = val
      // 获取员工列表
      this.getEmployeeList()
    },
    // 删除员工
    async handleDel(employeeId) {
      // 在删除之前，判断当前员工是否具备point-del这个权限点，
      // 如果没有，给个提示，直接return
      if (!this.$store.state.user.userInfo.roles.points.includes('point-del')) {
        return this.$message.warning('你没有删除权限，请联系管理员')
      }
      // 询问
      try {
        await this.$confirm('确定删除吗', '提示', {
          type: 'warning'
        })
        if (this.query.page > 1 && this.employeeList.length === 1) {
          this.query.page--
        }
        await delEmployeeAPI(employeeId)
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (err) {
        console.log(err)
      }

      // 确定
      // 发起删除请求
      // 获取员工列表
      // 给删除成功提示
      // 取消
    },
    // 下载excel
    handleDownload() {
      //  调用下载excel文件的方法
      const header = [
        '姓名',
        '部门',
        '手机号',
        '工号',
        '聘用形式',
        '入职日期',
        '转正日期'
      ]
      // 中英文键的对应关系
      const headerRalation = {
        手机号: 'mobile',
        姓名: 'username',
        聘用形式: 'formOfEmployment',
        入职日期: 'timeOfEntry',
        工号: 'workNumber',
        转正日期: 'correctionTime',
        部门: 'departmentName'
      }
      const data = this.employeeList.map((item) => {
        const arr = []
        header.forEach((zhKey) => {
          const enKey = headerRalation[zhKey]

          if (enKey === 'formOfEmployment') {
            const temp = obj.hireType.find((a) => a.id === +item[enKey])
            arr.push(temp ? temp.value : '未知')
          } else {
            arr.push(item[enKey])
          }
        })
        return arr
      })
      export_json_to_excel({
        header,
        data,
        filename: `${this.$store.state.user.userInfo.companyName}员工列表`
      })
    },
    async handleDownloadAll() {
      this.query.size = this.total
      this.query.page = 1
      await this.getEmployeeList()
      this.handleDownload()
    },
    // 分配角色弹框打开时
    async handleOpen(employeeId) {
      this.employeeId = employeeId
      this.isShow2 = true
      const resp1 = await getRoleListAPI({
        page: 1,
        pagesize: this.total
      })
      this.roleList = resp1.data.rows

      const resp2 = await getEmployeeInfoAPI(employeeId)
      this.checkedRoleList = resp2.data.roleIds
    },
    // 分配角色弹框关闭时
    handleClose() {
      this.isShow2 = false
      this.checkedRoleList = []
    },
    handleQrCode(url) {
      if (!url) return

      this.isShow = true
      // QrCode.toCanvas()

      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.qrCodeRef, url)
      })
    }
  }
}
</script>

<style>
.el-pagination {
  margin-top: 20px;
}
</style>
